package com.my.main.controller.microserviceInterface;

import com.alibaba.fastjson.JSONObject;
import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.common.encrypt.DES3;
import com.my.main.common.utils.DateUtil;
import com.my.main.common.utils.MultipartFileToFile;
import com.my.main.common.utils.StrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;


/**
 * 比对系统--上传文件接口
 * 只记录文件上传的路径，文件的存放位置实际在FSS文件服务上
 *
 * @author liuhx 2020-04-29
 */


//1.解决跨域
@CrossOrigin
//2.声明restContoller
@RestController
//3.设置父路径
@RequestMapping(value="/api/v1/file/uploadFile")
@Slf4j
public class CommonUpload extends BaseController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 系统--比对系统文件上传接口
     *
     * @param multipartFile 上传的文件
     * @describe fss 文件服务器不对外暴露，上传文件掉用此接口，由此接口内部调用fss文件上传接口
     * @author liuhx 2020-04-28
     */
    @ApiOperation(value="系统 - 比对系统文件上传接口", tags = NOINTERCEPT)
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result upload(MultipartFile multipartFile) throws UnsupportedEncodingException {

        JSONObject json = new JSONObject();
        log.info("使用RestTemplate调用模板上传专用接口");
        File toFile = null;
        try {
            toFile = MultipartFileToFile.multipartFileToFile(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件缓存发生异常:{}",e);
            return new Result(ResultCode.FAIL);
        }
        log.info("文件缓存到服务器,文件名:{}",toFile.getName());
        FileSystemResource resource = new FileSystemResource(toFile);
        //请求体参数
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        //文件
        param.add("file", resource);
        // 其他参数
        param.add("app_id", env.getProperty("cs.appId"));
        // json加密参数
        json.put("savePath", "/" + env.getProperty("app_key") + "/" + DateUtil.getFormatDate("yyyy/MMdd") + "/" + userInfo.getUserId());
        json.put("isOrigName", true);
        json.put("random", StrUtil.getRandomNumberString(6));
        StrUtil.getRandomNumberString(24);

        try {
            String encryptParams = DES3.encrypt(json.toString(), env.getProperty("app_secret"));
            param.add("params", encryptParams);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加密异常:{}",e);
        }

        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);

        //发送请
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(env.getProperty("fss.base.url") + "/fss/uploadFile", formEntity, String.class);
        System.out.println(URLDecoder.decode(stringResponseEntity.getHeaders().get("data").toString(), "UTF-8"));

        // 发送后删除本地缓存文件
        if (toFile != null && toFile.exists()) {
            toFile.delete();
        }

        return new Result(ResultCode.SUCCESS, URLDecoder.decode(stringResponseEntity.getHeaders().get("data").toString(), "UTF-8"),"操作成功");

    }


    /**
     * 比对系统--通过path获取文件url接口
     *
     * @param params 参数 {
     *               path: "", 保存路径
     *               app_id: ""    app_id
     * }
     * @describe fss 文件服务器不对外暴露，通过此接口获取文件Url
     * @author liuhx 2020-04-28
     */
    @ApiOperation(value="系统 - 通过path获取文件url接口")
    @RequestMapping(value = "/getUrlByPathApi", method = RequestMethod.POST)
    public Result getUrlByPath(@RequestBody Map<String,Object> params) throws UnsupportedEncodingException {
        System.out.println(params);
        log.info("使用RestTemplate调用文件Url地址获取专用接口");
        if (!StringUtils.isEmpty(params.get("app_id")) && !StringUtils.isEmpty(params.get("path"))) {

            System.out.println(env.getProperty("fss.base.url"));
            //请求体参数
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            //文件
            param.add("app_id", params.get("app_id"));
            // 其他参数
            param.add("path", params.get("path"));
            //请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
            //发送请求
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(env.getProperty("fss.base.url")+ "/fss/getUrl", formEntity, String.class);
            log.info("返回的URL:" + URLDecoder.decode(stringResponseEntity.getHeaders().get("data").toString(), "UTF-8"));
            return new Result(ResultCode.SUCCESS, URLDecoder.decode(stringResponseEntity.getHeaders().get("data").toString(), "UTF-8"),"操作成功");

        } else {
            return new Result(ResultCode.FAIL,"参数错误！");
        }
    }

}
